<template>
  <div class="externaltag al-height-full">
    <div class="tag-top-bar">
      <wx-tab-menu :tabs="topTabs" :tab-click="menuClick" :index="tagType">
        <template slot="right">
          <div class="bar-search">
            <el-input size="mini" v-model="keyword" clearable placeholder="输入标签名称" @keyup.enter.native="toSearch"/>
            <el-button size="mini" type="primary" @click="toSearch">搜索</el-button>
            <el-button size="mini" @click="keyword=''">重置</el-button>
          </div>
        </template>
      </wx-tab-menu>
    </div>

    <div class="manager-box al-height-full">
      <div class="manager-group-add">
        <el-button type="primary" @click="openAddGroupPopup">新增标签组</el-button>
        <div v-if="showQWSyntag" class="manager-qy-flex">
          <el-button type="success" @click="syncQiyeTags">同步企业标签</el-button>
          <wx-link type="default" style="font-size: 12px;">
            上限1万标签，目前已有标签数：
            <span style="color: #00afff">{{ getQiyeTagsCount() }}</span>
          </wx-link>
        </div>

      </div>

      <el-table :data="groupTableData">
        <el-table-column prop="groupName" label="标签组名称" width="280" :show-overflow-tooltip="true"/>
        <el-table-column prop="tag" label="标签">
          <template slot-scope="{row}">
            <div class="al-wx-tags">
              <el-tag size="mini" v-for="(tag,i) in row.tags">{{ tag.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="{row}">
            <wx-link @click.native="editTag(row)">编辑</wx-link>
            <wx-link type="danger" @click.native="deleteTagGroup(row)">删除</wx-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--  弹窗  -->
    <wx-tag-dialog ref="tagDialog" :refresh-tag="loadData"
                   @tagRemove="tagRemove"
                   @tagSubmit="tagSubmit"
                   @rename="tagSubmit"/>


    <el-dialog width="30%" title="新增分组" :visible.sync="addDialogOpen" append-to-body>
      <el-input v-model="addGroupForm.text" maxlength="15" show-word-limit/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddGroup">确定</el-button>
        <el-button @click="addDialogOpen=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import WxTabMenu from "@/components/wxqy/tabmenu/WxTabMenu";
import WxTable from "@/components/wxqy/table/WxTable";
import WxTagDialog from "@/components/wxqy/TagDialog/WxTagDialog";
import WxLink from "@/components/wxqy/wxLink/wxLink";
import {updateQiyeTags} from "@/api/wxqy/qiyeConfig";
import {
  addQywxContactTag,
  addQywxContactTagGroup, deleteQywxContactGroupTag,
  deleteQywxContactTag,
  qywxContactTagList
} from "@/api/wxqy/qiyeWeixinTag";

export default {
  name: "externaltag",
  components: {WxLink, WxTagDialog, WxTable, WxTabMenu},
  data() {
    return {
      addDialogOpen: false,
      showTagDialog: true,
      showQWSyntag: false,
      topTabs: ['', '企业微信标签'],
      // topTabs: ['自建标签', '企业微信标签'],
      tags: [],
      tagType: 1,
      keyword: '',
      addGroupForm: {},
      groupTableData: null
    }
  },
  methods: {
    loadData() {
      qywxContactTagList(this.tagType).then(e => {
        this.groupTableData = e.data
      })
    },
    menuClick(index) {
      this.showQWSyntag = index === 1
      this.tagType = index
      this.loadData()
    },
    editTag(row) {
      this.$refs.tagDialog.open(0, row)
    },
    openAddGroupPopup() {
      this.addGroupForm = {}
      this.addDialogOpen = true
    },
    submitAddGroup() {
      addQywxContactTagGroup({type: this.tagType, name: this.addGroupForm.text})
        .then(e => {
          this.loadData()
          this.$message.success('新增分组成功')
          this.addDialogOpen = false
        })
    },
    deleteTagGroup(row) {
      if (row.tags.length) {
        this.$message.error("该分组下仍存在标签，不能删除")
        return
      }
      this.$confirm('删除「' + row.groupName + '」标签组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQywxContactGroupTag(this.tagType, row.id).then(e => {
          this.loadData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      })
    },
    getQiyeTagsCount() {
      let sum = 0;
      this.groupTableData.forEach(e => sum += e.tags.length)
      return sum;
    },
    toSearch() {
      if (!this.backup) {
        this.backup = this.groupTableData
      }
      if (this.keyword) {
        let findTags = []
        for (const group of this.backup) {
          let tags = group.tags.filter(tag => tag.name.includes(this.keyword))
          findTags.push({
            groupName: group.groupName,
            tags: tags
          })
        }
        this.groupTableData = findTags
      } else {
        this.groupTableData = this.backup
      }
    },
    syncQiyeTags() {
      updateQiyeTags().then(e => {
        this.$message.success("已开始同步标签信息，请稍后...")
      })
    },
    tagSubmit(data, callBack) {
      data.type = this.tagType
      switch (data.t) {
        case 1: // 重命名分组
          addQywxContactTagGroup(data)
          break
        case 2:
          addQywxContactTag(data).then(e => {
            callBack(e.data.id)
            this.loadData()
          })
      }
    },
    tagRemove(id, callBack) {
      deleteQywxContactTag(this.tagType, id).then(e => {
        callBack()
        this.loadData()
      })
    }
  },
  created() {
    this.loadData()
  }
}
</script>

<style scoped lang="scss">
@import "../../../assets/styles/common";

.externaltag {
  margin: 20px;

  .tag-top-bar {
    position: sticky;
    top: 0;
    z-index: 10;
  }
}

.bar-search {
  @include flex-start;

  .el-button {
    margin-left: 10px;
  }
}

.tag-manager-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .tag-manager-icon {
    transform: rotate(-30deg);
    color: #00afff;
    margin-right: 4px;
    padding-top: 2px;
  }
}

.manager-box {
  border: 1px solid rgba(0, 0, 0, .1);
  background-color: #fff;
  border-radius: 20px 20px 4px 4px;

  .manager-group-add {
    margin: 10px 30px;
    display: flex;

    button {
      margin-right: 10px;
    }

    a:hover {
      color: #606266;
      cursor: text;
    }
  }

  .manager-qy-flex {
    display: flex;
    flex-direction: row;
    align-items: flex-end;
  }
}
</style>
